package com.qianda.qdminiapp.common.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;


/**
 * @author yan
 * @version V1.0
 * @date 2016-6-9 11:03:04
 * @desc
 */
public class HttpsUtil {

    public static final String get(final String url, final Map<String, Object> params) {
        StringBuilder sb = new StringBuilder("");

        if (null != params && !params.isEmpty()) {
            int i = 0;
            for (String key : params.keySet()) {
                if (i == 0) {
                    sb.append("?");
                } else {
                    sb.append("&");
                }
                sb.append(key).append("=").append(params.get(key));
                i++;
            }
        }

        CloseableHttpClient httpClient = createSSLClientDefault();

        CloseableHttpResponse response = null;
        HttpGet get = new HttpGet(url + sb.toString());
        String result = "";
//        Map<String,String> result = null;
        try {
            response = httpClient.execute(get);//response是https请求返回的信息
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException ex) {
                    Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        return result;
    }

    public static final String post(final String url, final Map<String, Object> params) {
        CloseableHttpClient httpClient = createSSLClientDefault();
        HttpPost post = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(7000).setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000).build();
        post.setConfig(requestConfig);

        CloseableHttpResponse response = null;

        if (null != params && !params.isEmpty()) {
            List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                NameValuePair nvp = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
                nvpList.add(nvp);
            }
            post.setEntity(new UrlEncodedFormEntity(nvpList, Charset.forName("UTF-8")));
        }

        String result = "";

        try {
            response = httpClient.execute(post);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException ex) {
                    Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        return result;
    }

    private static CloseableHttpClient createSSLClientDefault() {

        SSLContext sslContext;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(X509Certificate[] xcs, String string) {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyStoreException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (KeyManagementException ex) {
            Logger.getLogger(HttpsUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return HttpClients.createDefault();
    }

    public static void main(String[] args) throws InterruptedException {
        String url = "http://wxapp.wst1688.com/event/device/status";//检查状态
        String url2 = "http://wxapp.wst1688.com/admin/out/qqd_passthrough";//出巾命令
        String url3 = "http://wxapp.wst1688.com/admin/out/qqd_setLenth";//设置长度
        Map params = new HashMap<String, Object>();
        params.put("imei", "866289031525654");                        //设备imei
        params.put("user_id", "2017");
        params.put("key", "qqdwbdy");
        //params.put("tcpMsg", "0C00|00003| | |060.");

//        Map<String, Object> resultMap = new HashMap<>();
//        Gson gson = new Gson();
//        resultMap = gson.fromJson(HttpsUtil.post(url, params), resultMap.getClass());
//        //Map<String, Object> data = (Map<String, Object>) resultMap.get("data");
//        //System.out.println("返回的状态值为："+ data.get("status"));
//        if ((Double) resultMap.get("code") == 0.0) {
//            System.out.println("在线");
//        }
//
//        Map params1 = new HashMap<String, Object>();
//        params1.put("imei", "866289031525654");                        //设备imei
//        params1.put("user_id", "2017");
//        params1.put("key", "qqdwbdy");
//        params1.put("tcpMsg", "0C00|00003| | |060.");
//        resultMap = gson.fromJson(HttpsUtil.post(url3, params1), resultMap.getClass());
//        System.out.println("返回的值1为：" + resultMap);
//        if ((Double) resultMap.get("resultReturn") == 1) {
//            System.out.println("设置成功");
//        } else {
//            if (resultMap == null) {
//                System.out.println("没有权限");
//            }
//            System.out.println("设置未成功，重新发送设置命令");
//            resultMap = gson.fromJson(HttpsUtil.post(url3, params1), resultMap.getClass());
//            System.out.println("返回的值1为：" + resultMap);
//        }
//
//        //Thread.sleep(200);
//        Map params2 = new HashMap<String, Object>();
//        params2.put("imei", "866289031525654");                        //设备imei
//        params2.put("user_id", "2017");
//        params2.put("key", "qqdwbdy");
//        params2.put("tcpMsg", "0D00|20181128115750148348|01.");
//
//        Map<String, String> resultMap2 = new HashMap<>();
//
//        resultMap = gson.fromJson(HttpsUtil.post(url2, params2), resultMap.getClass());
      //  System.out.println("返回的值2为：" + resultMap2);
    }

}